package org.net5ijy.security.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.net5ijy.security.validate.ValidateCode;
import org.net5ijy.security.validate.ValidateCodeGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * ValidateCodeController
 *
 * @author XGF
 * @date 2020/11/30 22:39
 */
@Controller
public class ValidateCodeController {

  private static Logger log = LoggerFactory.getLogger(ValidateCodeController.class);

  @Autowired
  private Map<String, ValidateCodeGenerator> validateCodeGenerators = new HashMap<>();

  @RequestMapping(value = "/vCode", method = RequestMethod.GET)
  public void validateCode(String type, HttpServletRequest request,
      HttpServletResponse response) throws IOException {

    if (log.isDebugEnabled()) {
      log.debug("内置验证码生成器: " + validateCodeGenerators.toString());
    }

    // 根据type参数获取指定类型的验证码生成器
    ValidateCodeGenerator validateCodeGenerator =
        validateCodeGenerators.get(type + ValidateCodeGenerator.VALIDATE_GENERATOR_KEY_SUFFIX);
    // 如果没有获取到验证码生成器抛出一个异常
    if (validateCodeGenerator == null) {
      log.error("验证码生成器不存在: " + type);
      throw new RuntimeException("验证码生成器不存在: " + type);
    }
    // 生成验证码
    ValidateCode code = validateCodeGenerator.generateValidateCode(request, response);
    // 发送验证码
    validateCodeGenerator.sendValidateCode(code, request, response);
  }
}
